const express=require('express');
//创建WEB服务器
const mysql=require('mysql');
const pool=mysql.createPool({
	host:'127.0.0.1',
	port:'3306',
	user:'root',
	password:'',
	database:'tedu',
	connectionLimit:15
})
const app=express();
//设置端口
app.listen(3000,()=>{
	console.log('chengg')
});
//使用中间件将所有post请求的数据解析为对象
 app.use(express.urlencoded({
 	extended:false
 }))
//添加路由(post /v1/emps)
//接口地址:http://127.0.0.1:3000/v1/emps
//请求方法:post
/app.post('/v1/emps',(req,res)=>{
	//获取post请求的数据
	console.log(req.body);
	 pool.query('insert into emp set ?',[req.body],(err,result)=>{
	 if(err) throw err;
	 console.log(result);
	res.send({code:200,msg:'员工添加成功'})
}); 
	//执行SQL命令，将对象插入数据库tedu下的emp表中
	//res.json()和res.send()作用相同，都可以将对象转为json
	
});
//查找员工路由(get /v1/emps/编号)
//接口地址:http://127.0.0.1:3000/v1/emps/3
//请求方法:get
app.get('/v1/emps/:eid',(req,res)=>{
	//获取路由传参的数据
	//console.log(req.params);
	//执行SQL命令
		pool.query('select *from emp where eid=?',[req.params.eid],(err,result)=>{
		if(err) throw err;
		//console.log(result);
		if(result.length!==0){
			res.send({code:200,msg:'查找成功',data:result})
			}else{
				res.send({code:201,msg:'查找失败',data:'查无此人'})
			}
			
	});

})
app.delete('/v1/emps/:eid', (req, res) => {
	console.log(req.params);
	pool.query('delete from emp where eid=?', [req.params.eid], (err, result) => {
		if (err) throw err;
		console.log(result);
		//结果是对象，如果对象下的affectefRows值为0说明删除失败
		if (result.affectedRows == 1) {
			res.send({code: 200,msg: '删除成功'})
		}else{
			res.send({code:201,msg:'删除失败'})
		}
	})

})
